package com.xzsoft.gdwz.util;

import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Random;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Tools {
	public static String getRandomString(int length) { // length表示生成字符串的长度
		String base = "abcdefghijklmnopqrstuvwxyz0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	public static int getRandomInt(int max, int min) {
		Random random = new Random();
		int s = random.nextInt(max) % (max - min + 1) + min;
		return s;
	}

	public static Long getRandomLong() {
		Random random = new Random();
		Long s = random.nextLong();
		return s;
	}
	
	/**
	 * base64加密
	 * @param bytes
	 * @return
	 */
	public static String base64Encode(String str) {
		byte[] bytes = str.getBytes();
		return new BASE64Encoder().encode(bytes);
	}
	
	/**
	 * base64解密
	 * @param base64Code
	 * @return
	 * @throws Exception
	 */
	public static String base64Decode(String base64Code){
		String str = null;
		try {
			str = new String(new BASE64Decoder().decodeBuffer(base64Code));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return str;
	}
	
	public static void main(String[] args){
		System.out.println(base64Encode("123456"));
		System.out.println(base64Decode("MTIzNDU2"));
	}
	
	/**
	 * 获取mac地址
	 * @return
	 */
	public static String getLocalMac(){
		InetAddress ia;
		// 获取网卡，获取地址
		byte[] mac;
		String macAddre = null;
		try {
			ia = InetAddress.getLocalHost();
			mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
			StringBuffer sb = new StringBuffer("");
			for (int i = 0; i < mac.length; i++) {
				if (i != 0) {
					sb.append("-");
				}
				// 字节转换为整数
				int temp = mac[i] & 0xff;
				String str = Integer.toHexString(temp);
				if (str.length() == 1) {
					sb.append("0" + str);
				} else {
					sb.append(str);
				}
			}
			macAddre = sb.toString().toUpperCase();
			System.out.println("本机MAC地址:" + macAddre);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return macAddre;
	}
}
